const { ipcRenderer } = require('electron')
const jQuery = require('jquery')
const fs = require( 'fs' )
const path = require('path')
const moment = require('moment')

let btnPlFolder = document.querySelector('#btnPlFolder')
btnPlFolder.addEventListener('click', function(e){
  ipcRenderer.send('select-local-folder')
})

ipcRenderer.on('fill-folder-address', (event, url) => {
  let plFolder = document.querySelector('#plFolder')
  plFolder.value = url
  plFolder.setAttribute('title', url)
})

// 链接FTP服务器
let btnLinkFtp = document.querySelector('#btnLinkFtp')
btnLinkFtp.addEventListener('click', function(e){
  let _url = document.querySelector('#pfUrl').value
  let _port = document.querySelector('#pfPort').value
  let _name = document.querySelector('#pfName').value
  let _pwd = document.querySelector('#pfPwd').value

  let ftpObj = {
    url: _url,
    port: _port,
    name: _name,
    pwd: _pwd
  }

  ipcRenderer.send('start-ftp', ftpObj)
})

// 链接FTP服务器
let btnTaskStart = document.querySelector('#btnTaskStart')
btnTaskStart.addEventListener('click', function(e){
  let _pschedule = document.querySelector('#pschedule').value
  let _plFolder = document.querySelector('#plFolder').value

  let taskObj = {
    schedule: _pschedule,
    folder: _plFolder
  }
  
  ipcRenderer.send('task-start', taskObj)
})

// 关闭FTP服务链接
let btnCancelFtp = document.querySelector('#btnCancelFtp')
btnCancelFtp.addEventListener('click', function(e){
  ipcRenderer.send('cancel-ftp')
})

// 关闭任务
let btnCancelTask = document.querySelector('#btnCancelTask')
btnCancelTask.addEventListener('click', function(e){
  ipcRenderer.send('cancel-task')
})

ipcRenderer.on('record-info', (event, type, msg) => {
  let typeClass = type
  if (typeClass == 'close' || typeClass == 'disconnect'|| typeClass == 'notask') {
    typeClass = 'danger'
  }
  jQuery('.upload-info').prepend('<div class="alert alert-' + typeClass + '" role="alert"> ' + 
  '[' + moment().format('YYYY-MM-DD hh:mm:ss') + '] <strong>' + type + '</strong> '+ msg + '</div>')
})

let btnClose = document.querySelector('#btnClose')
btnClose.addEventListener("click", function(e) {
  ipcRenderer.send('close-app')
})


let inputPfUrl = document.querySelector('#pfUrl')
inputPfUrl.addEventListener("input", function(e) {
  setTimeout(() => {
    window.localStorage.setItem("pfUrl", inputPfUrl.value)
  }, 500)
})



